/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Compras;


import Controlador.Bean.Almacen.EntradaSalida;
import Controlador.Bean.Almacen.ProdxSolicitudMovimiento;
import Controlador.Bean.Almacen.SolicitudMovimiento;
import Controlador.Bean.Compras.ProductoxOrden;
import Controlador.Bean.RRHH.Personal;
import gui.Almacen.DetalleSolicitud;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author LiziTa
 */
public class PanelSolOrdenAlmc extends javax.swing.JPanel {

    /**
     * Creates new form PanelSolOrdenAlmc
     */
    PanelSolOrdenAlmc.TableModel tb;
    String estado;
    Date today;
    String id;
    String id2;
      public List<Personal> empleado;
    public PanelSolOrdenAlmc() {
      today = new Date();
        initComponents();
        initComp();
    }

       private void initComp() {
         tb = new TableModel();
        today = new Date();
         empleado=Controlador.Service.Compras.GestionCompra.obtenerPersonal();
         cmbEmpleado.removeAllItems();
        cmbEmpleado.addItem("Seleccionar");
         for(int i=0; i<empleado.size(); i++){
             cmbEmpleado.addItem(empleado.get(i).getNombre());
         }
                 
         
        tblOrden.setDefaultRenderer(JButton.class, new MiRender());
        tblOrden.setDefaultEditor( JButton.class, new MiEditor());
           
    }

       public class MiRender implements TableCellRenderer {
        // Este metodo indica como debe de pintarse el elemento en la fila row, en la columna column
        // que esta en la tabla table y tiene el color dado por el objeto.
        @Override
        public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) {    
            // como el boton y el calendario son componentes esto se vale.
            return (JComponent)table.getValueAt(row, column);
        }
     }
       
       public class MiEditor extends AbstractCellEditor implements TableCellEditor {
         private Boolean currentValue;
         @Override
         public Object getCellEditorValue()
         {
            return currentValue;
         }
         //El editor usara el propio componente. Para que funcione la celda en el modelo debe ser editable.
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
         {
           return (JComponent) value;// la tabla solo debe tener componentes graficos
         }
     }
    
       
        public void asignarNombre(TableModel tb){
        if(estado.compareTo("1")==0){
            String[] data = {"Id Orden", "Encargado", "Tipo", "Fecha", "Detalle", "Aceptar"};
            tb.columnNames = data;
        }else{
            String[] data = {"Id Orden", "Encargado", "Tipo", "Fecha", "Detalle"};
            tb.columnNames = data;
        }
        
    }
       
    class TableModel extends AbstractTableModel{
              
        //Two arrays used for the table data
        String[] columnNames = {"Id Orden", "Encargado", "Tipo", "Fecha", "Detalle"};
                    
        List<ProductoxOrden> data = Controlador.Service.Compras.GestionCompra.obtenerProdxOrden(id);
//        SolicitudMovimiento sm= Controlador.Service.Almacen.GestionAlmacenes.obtenerSolicitudMovimientoxIdMovimiento(id2);
        
        public void actualizarTabla(){
            data = Controlador.Service.Compras.GestionCompra.obtenerProdxOrden(id);
            fireTableDataChanged();
        }
        
        @Override
        public int getRowCount()
        {
            return data.size();
        }
        
        @Override
        public int getColumnCount()            
        {
            return columnNames.length;
        }
        
        @Override
        public Object getValueAt(int row, int column)
        {   
            if(estado.compareTo("1")!=0){
                switch(column){
                    case 0: return data.get(row).getIdOrdenCompra();
                    case 1: return data.get(row).getIdProducto();
                    case 2: return data.get(row).getCantidad();
                  
                    default: return new JButton("Detalle");
                }
            }else{
                switch(column){
                    case 0: return data.get(row).getIdOrdenCompra();
                    case 1: return data.get(row).getIdProducto();
                    case 2: return data.get(row).getCantidad();
                    case 3: return new JButton("Detalle");
                    default: return new JButton("Aceptar/Rechazar");
                }
            }
        }
        
        //Used by the JTable object to set the column names
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        //Used by the JTable object to render different
        //functionality based on the data type
        @Override
        public Class getColumnClass(int c) {
            if(c!=3){
            return getValueAt(0, c).getClass();
            }else{
                return JButton.class;
            }
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblOrden = new javax.swing.JTable();
        txtId = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cmbEmpleado = new javax.swing.JComboBox();

        tblOrden.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblOrden.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblOrdenMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblOrden);

        jLabel1.setText("Orden Compra");

        jLabel2.setText("Empleado");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(cmbEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(cmbEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tblOrdenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblOrdenMouseClicked
        
         int selectedRowIndex = tblOrden.getSelectedRow();
        int selectedColumnIndex = tblOrden.getSelectedColumn();
        if(selectedColumnIndex == 5){
            int resultado = JOptionPane.showConfirmDialog(this, "¿Desea aceptar la transacción?");
            if(resultado == JOptionPane.OK_OPTION){
                ProductoxOrden pxo = tb.data.get(tblOrden.getSelectedRow());
                  List<ProductoxOrden> ordenes = Controlador.Service.Compras.GestionCompra.obtenerProdxOrden(txtId.getText());
                 String idMov= Controlador.Service.Compras.GestionCompra.obtenerIdMov("Entrada");
                //List<SolicitudMovimiento> productos = Controlador.Service.Almacen.GestionAlmacenes.obtenerProdxSolicitudMovimiento(sm.getIdSolicitudMovimiento());
            
                Date fecha=new Date();
                
                 SolicitudMovimiento sm= new SolicitudMovimiento(idMov,empleado.get(cmbEmpleado.getSelectedIndex()-1).getIdEmpleado(),"ALM-3","Entrada",fecha,"Ingreso de Orden de Compra","0","OC");
                Controlador.Service.Almacen.GestionAlmacenes.agregarSolicitudMovimiento(sm);
                 for(int i=0; i<ordenes.size(); i++){
                ProdxSolicitudMovimiento pxsm= new ProdxSolicitudMovimiento(ordenes.get(i).getIdProducto(),idMov,Double.parseDouble(ordenes.get(i).getCantidad().toString()));
                //Controlador.Service.Almacen.GestionAlmacenes.agregarProdxSolMov(null, idMov, id);
                }
                tb.actualizarTabla();
                
            }else if(resultado == JOptionPane.NO_OPTION){
                //Controlador.Service.Almacen.GestionAlmacenes.eliminarSolicitudMovimiento(tb.data.get(selectedRowIndex));
            }
        }else if(selectedColumnIndex == 4){
           // DetalleSolicitud dt = new  DetalleSolicitud(tb.data.get(selectedRowIndex));
           // Main.getDesktop().add(dt);
            //(dt.setVisible(true);
        }
        
    }//GEN-LAST:event_tblOrdenMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cmbEmpleado;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblOrden;
    private javax.swing.JTextField txtId;
    // End of variables declaration//GEN-END:variables

 
}
